# -*- coding: utf-8 -*-
import hashlib
import json
import math
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://api.juzhikj.com/bank?parter={}&type={}&value={}&orderid={}&callbackurl={}&refbackurl={}&sign={}'
_QUERY_GATEWAY = 'http://api.juzhikj.com/search.ashx?orderid={}&parter={}&sign={}'

APP_CONF = {
    '1991': {
        #  盈信通支付 支付宝H5 2.5% 20-5000 LOKI
        #  盈信通支付 支付宝扫码 2.5% 20-5000 LOKI
        'API_KEY': 'bc107ecafb01496e9c17f1fa24cfbd2b',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = 'parter={}&type={}&value={}&orderid={}&callbackurl={}{}'.format(
        parameter['parter'], parameter['type'], parameter['value'],
        parameter['orderid'], parameter['callbackurl'], key)
    m = hashlib.md5()
    m.update(s.encode('gb2312'))
    sign = m.hexdigest()
    return sign


def generate_query_sign(parameter, key):
    '''  生成查询签名 '''
    s = 'orderid={}&parter={}{}'.format(
        parameter['orderid'], parameter['parter'], key)
    m = hashlib.md5()
    m.update(s.encode('gb2312'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    s = 'orderid={}&opstate={}&ovalue={}{}'.format(params['orderid'], params['opstate'],
                                                   params['ovalue'], key)
    m = hashlib.md5()
    m.update(s.encode('gb2312'))
    calculated_sign = m.hexdigest()
    if sign != calculated_sign:
        _LOGGER.info("yingxintongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipayscan':
        return 1003
    elif service == 'alipayh5':
        return 1006
    return 1003


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    service = info['service']
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('parter', app_id),
        ('type', _get_pay_type(service)),
        ('value', '%.2f' % math.ceil(pay_amount)),
        ('orderid', str(pay.id)),
        ('callbackurl', '{}/pay/api/{}/yingxintongpay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('hrefbackurl', '{}/pay/api/{}/yingxintongpay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
    ))
    p_dict['sign'] = generate_sign(p_dict, api_key)
    gate_url = _GATEWAY.format(p_dict['parter'], p_dict['type'], p_dict['value'],
                               p_dict['orderid'], p_dict['callbackurl'], p_dict['hrefbackurl'], p_dict['sign'])
    _LOGGER.info('yingxintongpay create: %s, order_id is: %s', json.dumps(p_dict), p_dict['orderid'])
    charge_resp.update({
        'charge_info': gate_url,
    })
    return charge_resp


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("yingxintongpay notify data: %s, order_is is: %s", json.dumps(data), data['orderid'])
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('yingxintongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['opstate']
    trade_no = data.get('sysorderid')
    total_fee = float(data['ovalue'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '0':
        _LOGGER.info('yingxintongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('orderid', pay_order.id),
        ('parter', app_id),
    ))
    p_dict['sign'] = generate_query_sign(p_dict, api_key)
    _LOGGER.info("yingxintongpay query data: %s, order_id is: %s", p_dict, p_dict['orderid'])
    gate_url = _QUERY_GATEWAY.format(p_dict['orderid'], p_dict['parter'], p_dict['sign'])
    response = requests.get(gate_url)
    if response.status_code == 200:
        # response text is a pure html text
        _LOGGER.info('yingxintongpay query response: %s', response.text)
        data = dict()
        for entry in response.text.split('&'):
            k, v = entry.split('=')
            data[k] = v
        verify_notify_sign(data, api_key)
        mch_id = pay_order.mch_id
        trade_status = data['opstate']
        total_fee = float(data['ovalue'])
        trade_no = pay_order.id

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee
        }

        if trade_status == '0' and total_fee > 0:
            _LOGGER.info('yingxintongpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
